from mod_python import apache
from mechanize import Browser
from mechanize import LinkNotFoundError
from mod_python.util import parse_qsl

def handler(req):
   	gets =  dict(parse_qsl(req.subprocess_env['QUERY_STRING']))
	req.log_error('handler')
	req.send_http_header()

	try:
	
		br = Browser()
		br.set_handle_robots(False)
		br.open("https://secure.lds.org/units/login/")
		br.select_form(nr=0)
		br['username']= gets['username']
		br['password'] = gets['password'] 
		response2 = br.submit()
		mylink = br.find_link(text="Ward Calendar")
		resp3 = br.follow_link(mylink) 
		mylink2 = br.find_link(text="iCal")
		resp4 = br.follow_link(mylink2)


	
		req.content_type = 'text/calendar'
		req.send_http_header()
		req.write(resp4.read())

	except LinkNotFoundError:
		req.content_type = 'text/plain'
		req.write("A 'LinkNotFoundError' has occurred.  One reason that links cannot be found is that the login was not successful")

	return apache.OK

